/*
1,安装axios  npm i axios
2,导入axios
3，创建axios副本
4，创建请求拦截，与响应拦截
5，暴露出去
*/
import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store/index'
import router from '@/router'

// 创建axios的副本对象
const _axios = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})

// 请求拦截器
_axios.interceptors.request.use(
  (config) => {
    config.headers.Authorization = `Bearer ${store.state.user.token}`
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 请求响应器
_axios.interceptors.response.use(
  (res) => {
    if (res.data.success) {
      return res.data
    } else {
      Message.error(res.data.message)
      return Promise.reject(res.data.message)
    }
  },
  (error) => {
    if (error.response.status === 401) {
      store.commit('user/logout')
      router.push('/login?redirect' + window.location.href.split('#')[1])
      Message.error('登陆超时')
    }
    return Promise.reject(error)
  }
)

export default _axios
